package com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.resp_ok;

import com.clp.protocol.core.utils.ByteUtil;
import com.clp.protocol.modbus_tcp.definition.ConstVal;
import com.clp.protocol.modbus_tcp.definition.MbByteOrder;
import com.clp.protocol.modbus_tcp.mb_frame.mb_body.mb_data.RespOkMbData;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ReadInputRegsRespOkMbData implements RespOkMbData {
    /**
     * 字节计数
     */
    private int byteCount;
    /**
     * 寄存器值列表
     */
    private List<Integer> regVals;

    @Override
    public ReadInputRegsRespOkMbData initBy(ByteBuf buf) {
        this.byteCount = buf.readByte() & 0xFF;
        this.regVals = new ArrayList<>(); byte[] valBytes = new byte[ConstVal.SET_REG_LEN];
        for (int i = 0; i < byteCount / ConstVal.SET_REG_LEN; i++) {
            buf.readBytes(valBytes);
            regVals.add(MbByteOrder.setRegOrder == ByteOrder.BIG_ENDIAN ?
                    ByteUtil.bytes2ToIntBE(valBytes) : ByteUtil.bytes2ToIntLE(valBytes));
        }
        return this;
    }

    @Override
    public boolean isValid() {
        if (byteCount < 0 || byteCount > 0xFF) return false;
        return regVals != null && byteCount / 2 == regVals.size();
    }

    @Override
    public void writeTo(ByteBuf buf) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("字节计数：" + byteCount + ", 寄存器值列表：");
        for (int i = 0; i < regVals.size(); i++) {
            sb.append(" " + regVals.get(i));
        }
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ReadInputRegsRespOkMbData that = (ReadInputRegsRespOkMbData) o;
        return byteCount == that.byteCount && Objects.equals(regVals, that.regVals);
    }

    @Override
    public int hashCode() {
        return Objects.hash(byteCount, regVals);
    }
}
